package com.kzd.gtboon

import android.content.Intent
import android.graphics.Color
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.*
import com.kzd.gtboon.app.AppFlowBus
import com.kzd.gtboon.app.GT_FORCE_LOGIN
import com.kzd.gtboon.base.BaseViewModel
import com.kzd.gtboon.databinding.ActivityMainBinding
import com.kzd.gtboon.entity.IsLogin
import com.kzd.gtboon.main.*
import com.kzd.gtboon.main.game.GameH5Activity
import com.kzd.gtboon.main.popup.AppUpDatePopup
import com.kzd.gtboon.main.popup.ProgressPopup
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.lang.Exception
import java.util.*

class MainActivity : OwnerViewBindingActivity<ActivityMainBinding>() {

    private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {

        override fun onFragmentResumed(fm: FragmentManager, fragment: Fragment) {
            super.onFragmentResumed(fm, fragment)
            when (fragment) {
                is MainHomeFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))

                    val distance = fragment.mViewModel.changeBarStyleLiveData.value ?: 0
                    val alpha = if (distance > 255) 255 else distance
                    val color = Color.argb(alpha, 41, 131, 255)
                    BarUtils.setStatusBarColor(fragment.requireActivity(), color)

                }
                is MainGameFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(
                        fragment.requireActivity(),
                        ColorUtils.getColor(R.color.colorMain)
                    )
                }
                is MainServiceFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                }
                is MainMineFragment -> {
                    BarUtils.setStatusBarLightMode(fragment.requireActivity(), (false))
                    BarUtils.setStatusBarColor(fragment.requireActivity(), Color.TRANSPARENT)
                }
            }
        }

    }

    private val mProgressPopup: ProgressPopup by lazy {
        ProgressPopup(context = this, onCancel = {}, onConfirm = {})
    }

    private val mAppUpDatePopup: AppUpDatePopup by lazy {
        AppUpDatePopup(context = this, onClick = {
            mAppUpDatePopup.dismiss()
            val fileUrl = mViewModel.userAppUpdateLiveData.value
                ?.data?.data?.apk_file_url ?: return@AppUpDatePopup
            mViewModel.userDownload(fileUrl) {
                mProgressPopup.setProgress(it)
            }
        })
    }

    private var mExitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                toast("再按一次退出程序")
                mExitTime = System.currentTimeMillis()
            } else {
                onBackPressed()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private var mCountdownJob: Job? = null

    private val mViewModel: BaseViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityMainBinding
        get() = ActivityMainBinding::inflate

    override fun initView() {

        val mainFragments: MutableList<Fragment> = mutableListOf(
            MainHomeFragment.newInstance(),
            MainGameFragment.newInstance(),
            MainServiceFragment.newInstance(),
            MainMineFragment.newInstance()
        )

        mViewBinding.viewPagerMain.offscreenPageLimit = mainFragments.size
        mViewBinding.viewPagerMain.setScrollAnim(false)
        mViewBinding.viewPagerMain.adapter = object : FragmentStatePagerAdapter(
            supportFragmentManager,
            BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getCount(): Int {
                return mainFragments.size
            }

            override fun getItem(position: Int): Fragment {
                return mainFragments[position]
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            }
        }

        mViewBinding.navViewMain.setOnNavigationItemSelectedListener { item ->
            val position = when (item.itemId) {
                R.id.item_main_game -> 1
                R.id.item_main_service -> 2
                R.id.item_main_mine -> 3
                else -> 0
            }
            mViewBinding.viewPagerMain.currentItem = position
            return@setOnNavigationItemSelectedListener true
        }

        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks,
            (true)
        )
    }

    override fun initData() {
        mViewModel.userAppUpDate(delay = 5000, id = 2)
    }

    override fun initViewMode() {
        mViewModel.userAppUpdateLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mAppUpDatePopup.setContent(data.update_log)
                .showPopupWindow()
        })
        mViewModel.userDownloadLiveData.observe(this as LifecycleOwner, { response ->
            when (response.status) {
                Status.START -> {
                    mProgressPopup.resetProgress()
                    mProgressPopup.showPopupWindow()
                }
                Status.FAILURE -> {
                    mProgressPopup.dismiss()
                    toast(response.error?.msg)
                }
                Status.SUCCESS -> {
                    mProgressPopup.dismiss()
                    val data = response.data?.data
                        ?: return@observe
                    AppUtils.installApp(data)
                }
            }
        })


        AppFlowBus.observe(this as LifecycleOwner,
            IsLogin::class.java, androidx.lifecycle.Observer<IsLogin> {
                ActivityUtils.finishActivity(GameH5Activity::class.java)
                if (!it.isLogin && GT_FORCE_LOGIN) {
                    toAccessActivity(AccessAction.LOGIN_CHANNEL)
                }
            })
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val mIndex = try {
            (intent?.extras?.getString(KEY_MAIN_INDEX) ?: "0").toInt()
        } catch (e: Exception) {
            0
        }
        when (mIndex) {
            3 -> mViewBinding.navViewMain.selectedItemId = R.id.item_main_mine
            2 -> mViewBinding.navViewMain.selectedItemId = R.id.item_main_service
            1 -> mViewBinding.navViewMain.selectedItemId = R.id.item_main_game
            else -> mViewBinding.navViewMain.selectedItemId = R.id.item_main_home
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        mCountdownJob?.cancel()
        supportFragmentManager.unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallbacks)
    }

}